package com.yunshu.yunshuapp.xianhuo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.yunshu.yunshuapp.ImageActivity;
import com.yunshu.yunshuapp.MainActivity;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.banner.ScrollBanner;
import com.yunshu.yunshuapp.kuaixun.KuaixundetailActivity;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.LoginActivity;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.views.CommonLoadingView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class XianhuoDetailActivity extends AppCompatActivity implements View.OnClickListener ,Toolbar.OnMenuItemClickListener, IWXAPIEventHandler, IWeiboHandler.Response {

    private Xianhuo model;
    private ScrollBanner banner;
    private List<String> productImages = new ArrayList<String>();
    private boolean mypost = false;
    private RelativeLayout maskView;
    private Button cancelButton;
    private RelativeLayout timeLine;
    private RelativeLayout session;
    private RelativeLayout weibo;

    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI;
    private CommonLoadingView loadingView;
    private ImageLoader mImageLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xianhuo_detail);

        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.setTitle("详细信息");
        bar.putInActivity(this);
        bar.setOnMenuItemClickListener(this);

        String xianhuoSerialized = getIntent().getStringExtra("xianhuo");
        ObjectMapper mapper = new ObjectMapper();
        try {
             model = mapper.readValue(xianhuoSerialized, Xianhuo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(getIntent().getStringExtra("mypost") != null){
            mypost = true;
        }
        refreshUI();

        View btn1 = findViewById(R.id.kucunbiaoBTN);
        if (model.getKucunpic()!= null && model.getKucunpic().length()>0) {
            btn1.setOnClickListener(this);
        }else{
            btn1.setVisibility(View.GONE);

        }

        View btn2 = findViewById(R.id.telBTN);
        btn2.setOnClickListener(this);

        maskView = (RelativeLayout) findViewById(R.id.maskLayout);
        timeLine = (RelativeLayout)findViewById(R.id.timeline);
        session = (RelativeLayout)findViewById(R.id.session);
        weibo = (RelativeLayout)findViewById(R.id.weibo);
        cancelButton = (Button)findViewById(R.id.cancelButton);
        timeLine.setOnClickListener(this);
        session.setOnClickListener(this);
        weibo.setOnClickListener(this);
        cancelButton.setOnClickListener(this);
        loadingView = (CommonLoadingView) findViewById(R.id.loadingView);
// 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();
        api = WXAPIFactory.createWXAPI(this, YSUtils.WXAPPID, false);
        api.registerApp(YSUtils.WXAPPID);
        api.handleIntent(getIntent(), this);

        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, YSUtils.WEIBOAPPID);
        mWeiboShareAPI.registerApp();
    }

    private void refreshUI() {
        initBanner();

        RelativeLayout auditLayout = (RelativeLayout) findViewById(R.id.auditLayout);
        if (!this.mypost){
            auditLayout.setVisibility(View.GONE);
        }else{
            TextView auditTV = (TextView) findViewById(R.id.auditTV);

            String audit = model.getAudit();
            if ("0".equalsIgnoreCase(audit)){
                auditTV.setText("待审核");
            }else if ("1".equalsIgnoreCase(audit)){
                auditTV.setText("审核通过");
            }else if ("2".equalsIgnoreCase(audit)){
                auditTV.setText("审核不通过");
            }

            TextView auditDesTV = (TextView) findViewById(R.id.auditDesTV);
            auditDesTV.setText(model.getAuditdesc());
        }

        TextView idTV = (TextView) findViewById(R.id.idTV);
        idTV.setText(model.getXianhuoId());

        TextView typeTV = (TextView) findViewById(R.id.typeTV);
        typeTV.setText(Integer.parseInt(model.getType()) == 0 ? "现货":"采购");

        TextView channelTV = (TextView) findViewById(R.id.channelTV);
        channelTV.setText(model.getChannelname());

        TextView factoryTV = (TextView) findViewById(R.id.factoryTV);
        factoryTV.setText(model.getFactory());

        TextView priceTV = (TextView) findViewById(R.id.priceTV);
        priceTV.setText(model.getPrice());

        TextView quanlityTV = (TextView) findViewById(R.id.quanlityTV);
        quanlityTV.setText(model.getQuality());

        TextView specificationTV = (TextView) findViewById(R.id.specificationTV);
        specificationTV.setText(model.getSpecification());

        if (model.getNumber() == null || model.getNumber().length() <= 0){
            LinearLayout layout = (LinearLayout) findViewById(R.id.numberLayout);
            layout.setVisibility(View.GONE);
        }else {
            TextView numberTV = (TextView) findViewById(R.id.numberTV);
            numberTV.setText(model.getFactory());
        }

        TextView storeHouseTV = (TextView) findViewById(R.id.storeHouseTV);
        storeHouseTV.setText(model.getStorehouse());

        TextView companyTV = (TextView) findViewById(R.id.companyTV);
        companyTV.setText(model.getCompany());

        TextView contactTV = (TextView) findViewById(R.id.contactTV);
        contactTV.setText(model.getContact());

        TextView telTV = (TextView) findViewById(R.id.telTV);
        telTV.setText(model.getTel());

        if (model.getMark() != null && model.getMark().length() > 0) {
            TextView companyMarkTV = (TextView) findViewById(R.id.companyMarkTV);
            companyMarkTV.setText(model.getCompanymark());
        }else{
            LinearLayout layout = (LinearLayout) findViewById(R.id.companymarkLayout);
            layout.setVisibility(View.GONE);
        }

        if (model.getMark() != null && model.getMark().length() > 0) {
            TextView markTV = (TextView) findViewById(R.id.markTV);
            markTV.setText(model.getMark());
        }else{
            LinearLayout layout = (LinearLayout) findViewById(R.id.markLayout);
            layout.setVisibility(View.GONE);
        }

        TextView auditTV = (TextView) findViewById(R.id.auditTV);
        auditTV.setVisibility(View.INVISIBLE);
    }

    private void initBanner() {
        banner = (ScrollBanner) findViewById(R.id.banner);

        if (model.getProductpic()!=null && model.getProductpic().length()>0){
            productImages.add(model.getProductpic());
        }
        if (model.getProductpic1()!=null && model.getProductpic1().length()>0){
            productImages.add(model.getProductpic1());
        }
        if (model.getProductpic2()!=null && model.getProductpic2().length()>0){
            productImages.add(model.getProductpic2());
        }
        if (productImages.size() == 0){
            banner.setVisibility(View.GONE);
            return;
        }
        int screenWidth = YSUtils.screenWidth(this); // 获取屏幕宽度
        ViewGroup.LayoutParams layout = banner.getLayoutParams();
        layout.width = screenWidth;
        layout.height = (int) (screenWidth*0.432) + 1;
        banner.setLayoutParams(layout);
        banner.setImages( productImages.toArray(new String[]{}) );
        banner.bannerClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int index = banner.indexOfView(v);
                Intent intent = new Intent();
                intent.setClass(XianhuoDetailActivity.this, ImageActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("imgUrl", productImages.get(index));
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        };
    }


    public void onClick(View v){
        if(v.getId() == R.id.kucunbiaoBTN){
            Intent intent = new Intent();
            intent.setClass(this, ImageActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("imgUrl",model.getKucunpic());
            intent.putExtras(bundle);
            this.startActivityForResult(intent,0);
        }else if(v.getId() == R.id.timeline){
            this.share2WX(SendMessageToWX.Req.WXSceneTimeline);

        }else if(v.getId() == R.id.session){
            this.share2WX(SendMessageToWX.Req.WXSceneSession);

        }else if(v.getId() == R.id.weibo){
            this.share2Weibo();

        }else if(v.getId() == R.id.cancelButton){
            maskView.setVisibility(View.INVISIBLE);

        }else{
            Intent phone = new Intent();
            phone.setData(Uri.parse("tel:" + model.getTel()));
            phone.setAction(Intent.ACTION_DIAL);
            //开启系统拨号器
            this.startActivity(phone);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share , menu);
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_share:
                maskView.setVisibility(View.VISIBLE);
                break;
            default:break;
        }
        return true;
    }


    private void share2Weibo() {
        if (mWeiboShareAPI.isWeiboAppInstalled()) {

            final WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息

            TextObject textObject = new TextObject();
            textObject.text = model.getAdvert();
            weiboMessage.textObject = textObject;
//            loadingView.setVisibility(View.VISIBLE);
//            loadingView.load();

            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = YSUtils.generateGUID();
            mediaObject.title = model.getAdvert();
            mediaObject.description = model.getAdvert();
            // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            mediaObject.setThumbImage(bitmap);
            mediaObject.actionUrl = shareURL();
            mediaObject.defaultText = "云数智惠";
            weiboMessage.mediaObject = mediaObject;
            SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
            request1.transaction = String.valueOf(System.currentTimeMillis());
            request1.multiMessage = weiboMessage;
            boolean b = mWeiboShareAPI.sendRequest(this,request1);//发送请求消息到微博，唤起微博分享界面

//            loadingView.setVisibility(View.VISIBLE);
//            loadingView.load();
//            mImageLoader.loadImage(model.getKucunpic(), new ImageLoadingListener() {
//                @Override
//                public void onLoadingStarted(String s, View view) { }
//
//                @Override
//                public void onLoadingFailed(String s, View view, FailReason failReason) {
//                    loadingView.setVisibility(View.INVISIBLE);
//                }
//
//                @Override
//                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//                    loadingView.setVisibility(View.INVISIBLE);
//
//                    WebpageObject mediaObject = new WebpageObject();
//                    mediaObject.identify = YSUtils.generateGUID();
//                    mediaObject.title = model.getAdvert();
//                    mediaObject.description = model.getAdvert();
//                    // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//                    float w = bitmap.getWidth();
//                    float h = bitmap.getHeight();
//                    bitmap = YSUtils.ratio(bitmap,100, 100/w * h);
//                    mediaObject.setThumbImage(bitmap);
//
//                    mediaObject.actionUrl = shareURL();
//                    mediaObject.defaultText = "云数智惠";
//                    weiboMessage.mediaObject = mediaObject;
//                    Boolean valiad = weiboMessage.checkArgs();
//                    SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
//                    request1.transaction = String.valueOf(System.currentTimeMillis());
//                    request1.multiMessage = weiboMessage;
//                    boolean b = mWeiboShareAPI.sendRequest(XianhuoDetailActivity.this,request1);//发送请求消息到微博，唤起微博分享界面
//                    System.out.println("11111"+b);
//                }
//
//                @Override
//                public void onLoadingCancelled(String s, View view) {
//                    loadingView.setVisibility(View.INVISIBLE);
//
//                }
//            });
        } else {
            Toast.makeText(this, "没有安装新浪微博客户端", Toast.LENGTH_LONG).show();
        }
    }

    private void share2WX(final int WXScene) {
        if (!api.isWXAppInstalled()){
            Toast.makeText(this, "未安装微信!", Toast.LENGTH_LONG).show();
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = this.shareURL();

        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = model.getAdvert();
        msg.description = model.getAdvert();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
        req.message = msg;
        req.scene = WXScene;
        boolean ret = api.sendReq(req);
        mImageLoader.loadImage(model.getKucunpic(), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                boolean ret = api.sendReq(req);
                loadingView.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                loadingView.setVisibility(View.INVISIBLE);

                float w = bitmap.getWidth();
                float h = bitmap.getHeight();

                bitmap = YSUtils.ratio(bitmap,100, 100/w * h);
                msg.setThumbImage(bitmap);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                boolean ret = api.sendReq(req);
            }

            @Override
            public void onLoadingCancelled(String s, View view) {
                loadingView.setVisibility(View.INVISIBLE);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                boolean ret = api.sendReq(req);
            }
        });


    }

    private String shareURL() {
        return "http://www.yunshutech.com/order.action#offer?id=" + model.getXianhuoId();
    }

    private  String logoURL(){
        return "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png";
    }

    @Override
    public void onResponse(BaseResponse baseResp) {//接收微客户端博请求的数据。

        switch (baseResp.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, "成功分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, "取消分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this, "分享到微博失败", Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                System.out.println("COMMAND_GETMESSAGE_FROM_WX");
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//                goToShowMsg((ShowMessageFromWX.Req) req);
                System.out.println("COMMAND_SHOWMESSAGE_FROM_WX");

                break;
            default:
                break;
        }
    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Toast.makeText(this, "成功分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
            default:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }
}
